﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using QuickApp.Core;
using EfSearchModel.Model;
using QuickApp.MVCControl;
using Resto.CostControl.Core;
using QuickApp.MVCControl.Form;
using Resto.CostControl.Core.Models;

namespace Resto.CostControl.Web.Controllers
{
    public class MaterialStorageController : Controller
    {
        private readonly IRepository<MaterialPurchase> _Repo;
        private readonly IRepository<MaterialPurchaseItem> _RepoItem;
        private readonly IRepository<Dish> _RepoDish;
        private readonly IUnitOfWork _UnitOfWork;
        private readonly IRepository<Storage> _RepoStorage;
        private readonly IRepository<Material> _RepoMaterial;
        private readonly IRepository<StockRecord> _RepoStockRecord;

        public MaterialStorageController(IRepository<MaterialPurchase> repo, IRepository<MaterialPurchaseItem> repoDM, IRepository<Dish> RepoDish, IRepository<Storage> RepoStorage, IRepository<Material> RepoMaterial, IRepository<StockRecord> RepoStockRecord, UnitOfWork unitOfWork)
        {
            _Repo = repo;
            _RepoItem = repoDM;
            _RepoDish = RepoDish;
            _RepoStorage = RepoStorage;
            _RepoMaterial = RepoMaterial;
            _RepoStockRecord = RepoStockRecord;
            _UnitOfWork = unitOfWork;
        }

        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public JsonResult Index(DWZPageInfo pageInfo, DWZQueryModel where)
        {
            where.AddItem("OrderState", "Delivery");
            var list = _Repo.GetPageable(pageInfo.ToPageInfo(), where);
            var fdata = pageInfo.ToFlexiGridData<MaterialPurchase>(list.Page.ToList(), list.Total);
            return Json(fdata);
        }

        public ActionResult Edit(string Id)
        {
            MaterialPurchase data = null;
            if (!string.IsNullOrWhiteSpace(Id))
            {
                data = _Repo.Find(Id);
            }
            else
            {
                data = new MaterialPurchase();
                data.Id = Guid.NewGuid().ToString();
                data.OrderDate = DateTime.Now;
            }
            return View(data);
        }

        [HttpPost]
        public JsonResult Save(MaterialPurchase data, IList<MaterialPurchaseItem> MaterialList)
        {
            JsonReturnMessages msg = new JsonReturnMessages();
            if (ModelState.IsValid)
            {
                try
                {
                    var oldData = _Repo.Find(data.Id);
                    oldData.OrderState = "Storage";
                    foreach (var m in MaterialList)
                    { 
                        //单位换算（斤=>克）
                        m.OrderCount = m.OrderCount * 500;
                        m.DeliveryCount = m.DeliveryCount * 500;
                        m.StorageCount = m.StorageCount * 500;

                        var childdata = _RepoItem.Find(m.Id);
                        childdata.DeliveryCount = m.DeliveryCount;
                        childdata.StorageCount = m.StorageCount;
                        childdata.State = "Storage";
                       
                        Storage Sordate = new Storage();
                        if (_RepoStorage.Find(s => s.MaterialId == m.MaterialId) == null)
                        {
                            var Material = _RepoMaterial.Find(m.MaterialId);
                            Sordate.Id = Guid.NewGuid().ToString();
                            Sordate.ActualSorage = m.StorageCount;
                            Sordate.MaterialId = m.MaterialId;
                            Sordate.Code = m.Code;
                            Sordate.Name = m.Name;
                            Sordate.Category = m.Category;
                            Sordate.Specification = Material.Specification;
                            Sordate.Unit = Material.Unit;
                            Sordate.Type = "RawMaterial";
                            Sordate.CurrentPrice = m.Price;
                            _RepoStorage.Insert(Sordate);
                        }
                        else
                        {
                            Sordate = _RepoStorage.Find(s => s.MaterialId == m.MaterialId);
                            Sordate.CurrentPrice = m.Price;
                            Sordate.ActualSorage += m.StorageCount;
                        }
                        
                        //保存库存记录
                        StockRecord StockRecorddate = new StockRecord() { 
                            Id = Guid.NewGuid().ToString(),
                            MaterialId = m.MaterialId,
                            Type = "采购入库",
                            Count =m.DeliveryCount,
                        };
                        _RepoStockRecord.Insert(StockRecorddate);
                    }

                    _UnitOfWork.Commit();
                    msg.IsSuccess = true;
                    msg.Msg = "操作成功";
                }
                catch (Exception ex)
                {
                    msg.IsSuccess = false;
                    msg.Msg = "操作失败：" + ex.Message;
                }
            }

            return Json(msg);
        }

        [HttpPost]
        public JsonResult Delete(string id)
        {
            JsonReturnMessages msg = new JsonReturnMessages();
            if (!string.IsNullOrEmpty(id))
            {
                try
                {
                    _Repo.Delete(id);
                    _UnitOfWork.Commit();
                    msg.IsSuccess = true;
                    msg.Msg = "操作成功";
                }
                catch
                {
                    msg.IsSuccess = false;
                    msg.Msg = "操作失败,请稍后重试！";
                }
            }
            else
            {
                msg.IsSuccess = false;
                msg.Msg = "参数错误";
            }
            return Json(msg);
        }

        [HttpPost]
        public JsonResult MaterialList(DWZPageInfo pageInfo, DWZQueryModel where)
        {
            var list = _RepoItem.GetPageable(pageInfo.ToPageInfo(), where);
            var fdata = pageInfo.ToFlexiGridData<MaterialPurchaseItem>(list.Page.ToList(), list.Total);
            return Json(fdata);
        }

        public ActionResult EditList()
        {
            return View();
        }

        [HttpPost]
        public JsonResult EditList(string parentId, DWZPageInfo pageInfo, DWZQueryModel where)
        {
            where.AddItem("OrderId", parentId == "" ? null : parentId);
            var list = _RepoItem.GetPageable(pageInfo.ToPageInfo(), where);
            var pageList = list.Page.ToList();
            foreach (var item in pageList)
            {
                item.OrderCount = item.OrderCount / 500;
                item.DeliveryCount = item.DeliveryCount / 500;
                item.StorageCount = item.StorageCount / 500;
            }
            var fdata = pageInfo.ToFlexiGridData<MaterialPurchaseItem>(pageList, list.Total);
            return Json(fdata);
        }

        [HttpPost]
        public JsonResult DeleteItem(string Id)
        {
            JsonReturnMessages msg = new JsonReturnMessages();
            if (!string.IsNullOrEmpty(Id))
            {
                try
                {
                    _RepoItem.Delete(Id);
                    _UnitOfWork.Commit();

                }
                catch
                {
                    msg.IsSuccess = false;
                    msg.Msg = "操作失败,请稍后重试！";
                }
            }
            else
            {
                msg.IsSuccess = false;
                msg.Msg = "参数错误";
            }
            return Json(msg);
        }

        [HttpPost]
        public JsonResult Storage(string Id)
        {
            try
            {
                var data = _Repo.Find(Id);
                data.OrderState = "ruku";

                var itemList = _RepoItem.FindAll(m => m.OrderId == Id).ToList();
                foreach (var childitem in itemList)
                {
                    var childdata = _RepoItem.Find(childitem.Id);
                    childdata.State = "ruku";

                    Storage Sordate = new Storage();

                    if (_RepoStorage.Find(m => m.MaterialId == childdata.MaterialId) == null)
                    {
                        Sordate.Id = Guid.NewGuid().ToString();
                        Sordate.ActualSorage = childdata.OrderCount;
                        Sordate.MaterialId = childdata.MaterialId;
                        Sordate.Code = childdata.Code;
                        Sordate.Name = childdata.Name;
                        Sordate.Category = childdata.Category;
                        Sordate.Type = "RawMaterial";
                        Sordate.CurrentPrice = childdata.Price;
                        _RepoStorage.Insert(Sordate);
                    }
                    else
                    {
                        Sordate = _RepoStorage.Find(childdata.MaterialId);
                        Sordate.CurrentPrice = childdata.Price;
                        Sordate.ActualSorage = +childdata.OrderCount;

                    }


                }

                _UnitOfWork.Commit();
            }
            catch (Exception ex)
            {
                throw ex;
            }

            var result = new JsonReturnMessages
            {
                IsSuccess = true,
                Msg = "操作成功",
            };
            return Json(result);
        }

    }
}
